import time

import requests
import json

import shutil
import os
import io
import threading

from dashscope import Thread


def get_url(url):
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return json.loads(response.text)
    else:
        print(f"请求失败，原因：{response.text}")
        return None


# 语雀API的Base URL和端点
base_url = "https://se2024.yuque.com/api/v2/"

# 你的认证信息，比如Token或其他认证方式
headers = {
    "X-Auth-Token": "daUnVbO1WzxhSiIo8bo2wkP2rKbDxjYpz0KD2Vy9",
    "Content-Type": "application/json",
    "X-Csrf-Token": "ouY6csTu-22dcyWS1M1vzyMS",
    "Referer": "https://se2024.yuque.com/org-wiki-se2024-go4lg1/kmyk33/pf0wupluuld8lho9",
    "Cookie": "lang=zh-cn; lang=zh-cn; _yuque_session=GjmDSBKgdOqFpJrwqFMTeWLU4LEwORq57qqJ7crdBU1MCD-jzhr9Yvf_T6TZ2yTtBfjg06Ftuz9fNFzNpxGJ_Q==; receive-cookie-deprecation=1; yuque_ctoken=ouY6csTu-22dcyWS1M1vzyMS; aliyungf_tc=81255cf344f0aaf1e715cf854371814804ed307fd930d9195a1fe70ee3d3a544; current_theme=default; acw_tc=ac11000117206336754746802e6df6c159ddd9de5fb189bfc8fa903aa98482"
}
wiki_url = "https://se2024.yuque.com/api/modules/org_wiki/wiki/show?organizationId=21006641"
# 获得公共空间的数据
wiki_info = get_url(wiki_url)
# 获得公共空间的个人实验报告知识库列表
personal_book_data = wiki_info["layouts"][0]['placements'][0]['blocks'][1]['data'][2]['books']
book_id_dict = {}
for book in personal_book_data:
    book_id_dict[book['name']] = {}
    book_id_dict[book['name']]['id'] = book['id']
    book_id_dict[book['name']]['slug'] = book['slug']
    book_id_dict[book['name']]['user_id'] = book['user_id']
    book_id_dict[book['name']]['user'] = book['user']
temp_book = book_id_dict['实验2~报告收集知识库']
# 获取文档列表
doc_list_url = "https://se2024.yuque.com/api/docs?book_id=" + str(temp_book['id'])
doc_list_response = get_url(doc_list_url)
doc_list = doc_list_response["data"]
for temp_doc in doc_list:
    print(temp_doc["title"]+"开始下载==================================")
    export_data = {
        "type": "pdf",
        "force": 0,
        "options": "{}"
    }

    export_url = "https://se2024.yuque.com/api/docs/" + str(temp_doc['id']) + "/export"
    # 这个export_response第一次返回的是pending第四次返回的是success
    export_response = requests.post(export_url, headers=headers, data=json.dumps(export_data))
    # 如果是4xx或5xx状态码，打印错误信息
    if export_response.status_code >= 400:
        print(f"请求失败，原因：{export_response.text} {temp_doc}")
        continue
    while export_response.json()["data"]["state"] == "pending":
        time.sleep(3)
        export_response = requests.post(export_url, headers=headers, data=json.dumps(export_data))
        print(temp_doc["title"] + " 导出中" +export_response.json()["data"]["state"])
        # 如果是4xx或5xx状态码，打印错误信息
        if export_response.status_code >= 400:
            print(f"请求失败，原因：{export_response.text} {temp_doc}")
            break
        if export_response.json()["data"]["state"] == "success":
            print(temp_doc["title"] + " 导出完成" + export_response.json()["data"]["state"])
            break
    # download_url是含有PDF的链接
    download_url = "https://se2024.yuque.com" + export_response.json()["data"]["url"]

    # 将文件下载到本地

    # 将文件下载到本地
    file_response = requests.get(download_url, headers=headers)

    # 确保响应状态码为200
    if file_response.status_code == 200:
        # 确保目录存在
        os.makedirs("./second/", exist_ok=True)

        # 确保文件名是有效的
        file_name = str(temp_doc['id']) + ".pdf"
        file_path = os.path.join("./second/", file_name)
        bytes_io = io.BytesIO(file_response.content)
        # 使用shutil.copyfileobj将响应内容（已解压缩）写入文件
        with open(file_path, 'wb') as f:
            f.write(bytes_io.getvalue())
            print(temp_doc["title"] + " 下载成功！")
    else:
        print(f"文件下载失败，HTTP状态码：{file_response.status_code}")

